package codeTopPractice;

import java.util.LinkedList;

public class K个一组反转链表 {

    public static void main(String[] args) {
        // 测试git 提交
        System.out.println("test git");
    }

    public static ListNode reverseKGroup(ListNode head,int k){
        ListNode result = new ListNode(0);
        result.next = head;

        ListNode pre = result;
        ListNode end = result;

        while (end.next!=null){
            for (int i = 0; i < k && end !=null; i++) {
                end=end.next;
            }
            if(end == null) break;
            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;
            pre.next = reverse(start);
            start.next = next;
            pre = start;
            end = start;

        }
        return result.next;
    }

    public static ListNode reverse(ListNode head){

        if(head == null || head.next == null){
            return head;
        }
        ListNode pre = null;
        ListNode curr = head;
        while (curr !=null){
            ListNode next = curr.next;
            curr.next = pre;
            pre  = curr;
            curr = next;
        }
        return pre;
    }


}

class ListNode {

    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
